package com.topfun.utils;

import com.topfun.vo.AccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by Administrator on 2015/11/12.
 */
public class WsJsUtil {
    private static Logger logger = LoggerFactory.getLogger(WsJsUtil.class);
    /**
     * @param url 当前网页的URL，不包含#及其后面部分
     * @return
     */
    public static String getParam(String url) {
        AccessToken accessToken = WechatUtil.accessToken;
        if(null == accessToken){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getParam(url);
        }else{
            Map<String, String> params = sign(WechatUtil.accessToken.getTicket(), url);
            params.put("appId", Constants.WeChat_App_ID);
            return GsonUtil.toJson(params);
        }
    }


    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret       = new HashMap<>();
        String              nonce_str = create_nonce_str();
        String              timestamp = create_timestamp();
        String              str;
        String              signature = "";

        //注意这里参数名必须全部小写，且必须有序
        str = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(str.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (Exception e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        logger.info(GsonUtil.toJson(ret));
        return ret;
    }

/*    public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        String str = "jsapi_ticket=HoagFKDcsGMVCIY2vOjf9h4LC0bJajOp34AKsexYk5yfJKoB-qTwjW6YB4Ov8EIduIiN7JEWhS4ogIOh4tG58Q&noncestr=cd5b8889-b616-4212-bb2c-29d79e691b94&timestamp=1506597796&url=http://www.tuiclubs.com//WEB-INF/views/index.jsp?code\\u003d061dSfaZ18zLYY07OhbZ1zqU9Z1dSfa0\\u0026state\\u003d";
        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(str.getBytes("UTF-8"));
        System.out.println(byteToHex(crypt.digest()));
    }*/
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    //获取当前系统时间 用来判断access_token是否过期
    public static String getTime() {
        Date             dt  = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(dt);
    }
}
